<!--
 * @Author: qiaoxin
 * @Date: 2024-04-09 19:35:26
 * @LastEditors: qiaoxin
 * @LastEditTime: 2024-04-16 12:03:50
 * @Description: 
 * @FilePath: \erp-app\src\pages\pm\requirement\detail.vue
-->

<route lang="json5">
{
  layout: 'default',
  style: {
    navigationBarTitleText: '需求结论评审',
    enablePullDownRefresh: true,
    navigationStyle: 'custom',
  },
}
</route>

<template>
  <page-meta :root-font-size="setting.rootFontSize"></page-meta>
  <view style="min-height: 100vh; background-color: #f2f2f1">
    <view style="position: sticky; top: 0; z-index: 9999">
      <wd-navbar title="需求结论评审" :bordered="false" safeAreaInsetTop>
        <template #left>
          <wd-icon name="thin-arrow-left" size="22px" color="white" @click="goBack"></wd-icon>
        </template>
      </wd-navbar>
    </view>

    <view style="flex: 1; overflow: auto">
      <th-card title="基础信息">
        <th-form>
          <th-form-item label="单据编号">
            <text class="text">{{ form.demandCode }}</text>
          </th-form-item>
          <th-form-item label="日期">
            <text class="text">{{ formatByDayjs(form.demandDate) }}</text>
          </th-form-item>
          <th-form-item label="客户" v-if="form.cusFlag == '0'">
            <text class="text">{{ form.cusCode }}</text>
          </th-form-item>
          <th-form-item :label="form.cusFlag == '0' ? '业务员' : '需求人'">
            <text class="text">{{ form.personName }}</text>
          </th-form-item>
          <th-form-item label="业务部门">
            <text class="text">{{ form.deptName }}</text>
          </th-form-item>
        </th-form>
      </th-card>
      <th-card title="产品需求信息">
        <th-form>
          <th-form-item label="需求类型">
            <text class="text">{{ form.demandType }}</text>
          </th-form-item>
          <th-form-item label="需求产品">
            <text class="text">{{ form.invName }}</text>
          </th-form-item>
          <!-- <th-form-item label="指标" v-if="isShowCheckTarget" class="form-CheckTarget">
              <wd-table :data="checkTargetList">
                <wd-table-col prop="cchkguidename" label="检验指标名称" width="33%"></wd-table-col>
                <wd-table-col prop="checktarget" label="U8指标" width="33%"></wd-table-col>
                <wd-table-col prop="cusCheckTarget" label="客户指标" width="34%"></wd-table-col>
              </wd-table>
            </th-form-item> -->

          <th-form-item label="需求产品规格">
            <text class="text">{{ form.invStd }}</text>
          </th-form-item>
          <th-form-item label="应用领域">
            <text class="text">{{ form.applicationType }}</text>
          </th-form-item>
          <th-form-item label="年需求量/吨">
            <text class="text">{{ form.invDemand }}</text>
          </th-form-item>
          <th-form-item label="是否有外来样">
            <text class="text">{{ form.sampleFlagName }}</text>
          </th-form-item>
          <th-form-item label="样品编码" v-if="form.sampleFlag != '0'">
            <text class="text">{{ form.sampleCode }}</text>
          </th-form-item>
          <th-form-item label="需求样品数量" v-if="form.sampleFlag != '0'">
            <text class="text">{{ form.samplesNum }}{{ form.sampleUnit }}</text>
          </th-form-item>
          <th-form-item label="来样批次" v-if="form.sampleFlag != '0'">
            <text class="text">{{ form.sampleBatch }}</text>
          </th-form-item>
          <th-form-item label="要求完成时间">
            <text class="text">{{ formatByDayjs(form.askCompleteTime) }}</text>
          </th-form-item>
          <th-form-item label="需求描述" class="form-demandDesc">
            <text class="text">{{ form.demandDesc }}</text>
          </th-form-item>
          <th-form-item label="评审结论" class="form-demandDesc">
            <text class="text">{{ reviewForm.deviceResult }}</text>
          </th-form-item>
          <th-form-item label="评审结果">
            <text class="text">
              <view v-if="reviewForm.deviceStatus == '1'" class="result-tag">通过</view>
              <view
                v-else-if="reviewForm.deviceStatus == '0'"
                class="result-tag"
                style="background-color: #f50"
              >
                不通过
              </view>
            </text>
          </th-form-item>
          <!-- <th-form-item label="预计完成时间">
            <text class="text">{{ formatByDayjs(form.completeTime) }}</text>
          </th-form-item> -->

          <!-- <th-form-item label="技术负责人">
              <text class="text">{{ form.technologyHeadName }}</text>
            </th-form-item> -->
          <th-form-item
            v-for="item in rdProjectUserList.filter((item) => item.chooseFlag == 1)"
            :label="item.documentsPostName"
            :key="item.id"
          >
            <text class="text">{{ getProjectName(item) }}</text>
          </th-form-item>
          <!-- <th-form-item label="项目成员" class="form-demandDesc">
            <text class="text">{{ getProjectName({ documentsPostCode: 0 }) }}</text>
          </th-form-item> -->

          <!-- <th-form-item label="备注">
            <text class="text">{{ form.remark }}</text>
          </th-form-item> -->
        </th-form>
      </th-card>

      <th-card title="需求指标" v-if="isShowCheckTarget">
        <view style="overflow: auto" class="table-container">
          <table class="analysis-table">
            <tbody>
              <tr>
                <th style="width: 320rpx; min-width: 9.5rem">检验指标名称</th>
                <th style="width: 280rpx; min-width: 280rpx">U8指标</th>
                <th style="width: 280rpx; min-width: 280rpx">客户指标</th>
              </tr>
              <tr align="center" v-for="(item, index) in checkTargetList" :key="index">
                <td>
                  <view>
                    {{ item.cchkguidename }}
                  </view>
                </td>
                <td>
                  <view>
                    {{ item.checktarget }}
                  </view>
                </td>
                <td>
                  <view>
                    {{ item.cusCheckTarget }}
                  </view>
                </td>
              </tr>
            </tbody>
          </table>
        </view>
      </th-card>

      <th-card title="评审人员签字">
        <th-form>
          <!-- <th-form-item label="副总工">
              <wd-img
                :width="200"
                :height="100"
                :src="form.deputyChiefEngineerUrl"
                @click="preview(form.deputyChiefEngineerUrl)"
              />
            </th-form-item>
            <th-form-item label="总工">
              <wd-img
                :width="200"
                :height="100"
                :src="form.chiefEngineerUrl"
                @click="preview(form.chiefEngineerUrl)"
              />
            </th-form-item> -->
          <!-- rdProjectUserList -->

          <th-form-item
            v-for="item in reviewForm.rdProjectUserEntity.filter((item) => item.signatureFlag == 1)"
            :label="item.documentsPostName"
          >
            <wd-img
              :width="200"
              :height="100"
              :src="getProjectName(item, 1)"
              @click="preview(getProjectName(item, 1))"
            />
          </th-form-item>
        </th-form>
      </th-card>

      <!-- <view :class="['sign-main', 'bg-white', showSign ? '' : 'sign-gray']" @click="sign">
          签字
        </view> -->
      <view :class="['sign-main', 'bg-white']" @click="sign">签字</view>

      <wd-action-sheet v-model="showAction" title="" @close="closeSign" @click-modal="closeSign">
        <view class="sign-main-show">
          <!-- <text class="sign-main-show-title">签字</text> -->
          <view class="sign-main-show-line">
            <!-- <wd-img :width="200" :height="100" :src="signature" @click="preview(signature)" /> -->
            <wd-img :width="200" :height="100" :src="signature" @click="signThis" />
          </view>
          <!-- <view class="sign-main-show-btn" @click="signThis">使用该签字</view> -->
          <view class="sign-main-show-btn" @click="signReset">重新签字</view>
        </view>
      </wd-action-sheet>
    </view>
  </view>
</template>

<script lang="ts" setup>
import { useSetting } from '@/stores/setting';
import signV from '../../index/sign.vue';
import {
  getByIdSqlDevice,
  getPersonByPersonCode,
  updateByIdEvery,
  uploadSignature,
  selectrdDocumentsPostUser,
  updaterdProjectUser,
  selectrdDocumentsPostDict,
  updateSignHandle,
  getrdDemandDeviceObj,
} from '@/service/pm-requirement';
import { formatByDayjs } from '@/utils/util';
import { useUserStore } from '@/stores/user';

const setting = useSetting();
const userStore = useUserStore();
const showSign = ref(false);
const signature = ref('');
const userInfo = ref({});
const isChiefEngineer = ref('');
const isDeputyChiefEngineer = ref('');
const showAction = ref(false);
const isShowCheckTarget = ref(false);
const checkTargetList = ref([]);
const postUserObj: any = ref({});
const rdProjectUserList = ref([]); // 签名列表

// 提交表单数据
const form = reactive({
  id: '',
  demandDate: '',
  personName: '',
  demandType: null,
  deptHead: '',
  deptCode: '',
  applicationType: '',
  samplesNum: '',
  demandDesc: '',
  sampleCoding: '',
  askCompleteTime: null,
  taskCode: '',
  userCode: '',
  invName: '',
  invDemand: '',
  sampleFlag: null,
  demandCode: '',
  cusName: '',
  personCode: '',
  deptHeadCode: '',
  cusFlag: '0',
  deviceResult: '',
  completeTime: '',
  // technologyHead: '',
  // technologyHeadName: '',
  remark: '',
  // technologyHeadCode: '',
  taskId: null,
  instanceId: '',
  invStd: '',
  sampleCode: '',
  sampleBatch: '',
  deptName: '',
  deviceStatus: null,
  chiefEngineer: '',
  deputyChiefEngineer: '',
  status: '',
  sampleFlagName: '',
  deputyChiefEngineerUrl: '',
  chiefEngineerUrl: '',
  sampleUnit: '',
  cusCode: null,
  rdProjectUserEntity: [],
});

const reviewForm = reactive({
  id: null,
  reviewStatus: null,
  deviceStatus: null,
  rdProjectUserEntity: [],
});

const init = (id) => {
  uni.$off('pm-requirement-sign');
  selectrdDocumentsPostDictList();
  uni.showLoading({
    mask: true,
  });
  isShowCheckTarget.value = false;
  getByIdSqlDevice({ id })
    .then((res) => {
      console.log('res', id, res);
      Object.assign(form, res.data);

      if (res.data.rdDemandStandard && res.data.rdDemandStandard.length) {
        isShowCheckTarget.value = true;

        checkTargetList.value = res.data.rdDemandStandard.map((item) => {
          return {
            ...item,
            cchkguidename: item.standardName,
            cchkguidecode: item.standardCode,
            checktarget: item.standardValue,
            cusCheckTarget: item.standardValuePm,
          };
        });
      }
      getrdDemandDeviceObjHandle();
    })
    .finally(() => {
      uni.hideLoading();
      uni.stopPullDownRefresh();
    });
  // checkPost();

  selectrdDocumentsPostUserFn();
};

onLoad((options) => {
  const params = JSON.parse(options.params);
  const id = params.id;
  reviewForm.id = params.deviceId;
  console.log('opp', id);

  // const demandCode = params.demandCode;
  init(id);
});

const sign = () => {
  // if (!showSign.value) return;
  // 判断签字
  const userInfos = userStore.userInfos;
  const cusPerson = userInfos.user.username;
  getPersonByPersonCode({
    personCode: cusPerson,
  }).then((res) => {
    const sign = res.data.signature;
    signature.value = sign;
    userInfo.value = res.data;
    if (sign) {
      showAction.value = true;
    } else {
      uni.$on('pm-requirement-sign', (e) => {
        console.log('sign', e);
        signHanle(e);
      });
      uni.navigateTo({
        url: '/pages/pm/requirement/autograph',
      });
    }
  });

  // uni.navigateTo({
  //   url: '/pages/pm/requirement/autograph',
  // });
};

onPullDownRefresh(() => {
  init(form.id);
});

const goBack = () => {
  uni.navigateBack();
};

// uni.$on('pm-requirement-sign', (e) => {
//   console.log('sign', e);
//   signHanle(e);
// });

const preview = (url) => {
  if (!url) return;
  uni.previewImage({
    urls: [url],
  });
};

const closeSign = () => {
  showAction.value = false;
  uni.$off('pm-requirement-sign');
};

let signT = new Date().getTime();
const signHanle = (sign) => {
  let nSignT = new Date().getTime();
  if (nSignT - signT < 1000) {
    return;
  }
  console.log('-----');
  signT = new Date().getTime();
  const userInfos: any = userInfo.value;
  // // 判断岗位
  // const _isChiefEngineer = isChiefEngineer.value;
  // const _isDeputyChiefEngineer = isDeputyChiefEngineer.value;

  // const params = {
  //   id: form.id,
  // };

  // if (!_isChiefEngineer && !_isDeputyChiefEngineer) {
  //   uni.showToast({
  //     title: '只有总工和副总工才能签字',
  //     icon: 'none',
  //   });
  //   return;
  // }

  // if (_isChiefEngineer) {
  //   // params['chiefEngineer'] = userInfos.id;
  //   params['chiefEngineer'] = userInfos.personCode;
  //   params['chiefEngineerName'] = userInfos.personName;
  //   params['chiefEngineerPost'] = _isChiefEngineer;
  //   params['chiefEngineerUrl'] = sign;
  // } else if (_isDeputyChiefEngineer) {
  //   params['deputyChiefEngineer'] = userInfos.personCode;
  //   params['deputyChiefEngineerName'] = userInfos.personName;
  //   params['deputyChiefEngineerPost'] = _isDeputyChiefEngineer;
  //   params['deputyChiefEngineerUrl'] = sign;
  // }
  // const userInfos: any = userStore.userInfos;
  const params = {
    personId: userInfos.id,
    userName: userInfos.personName,
    userCode: userInfos.personCode,
    userUrl: sign,
    // userType: postUserObj.value.documentsPostCode,
    documentsPostName: postUserObj.value.documentsPostName,
    documentsPostCode: postUserObj.value.documentsPostCode,
    documentsName: postUserObj.value.documentsName,
    documentsCode: postUserObj.value.documentsCode,
    signatureFlag: postUserObj.value.signatureFlag,
    reviewFlag: postUserObj.value.reviewFlag,
    rdCode: reviewForm.deviceCode,
    successFlag: reviewForm.deviceStatus,
  };

  console.log('postUserObj', params);

  uni.showLoading({
    mask: true,
  });
  updateSignHandle(params)
    .then((res) => {
      if (res.code == 0) {
        uni.showToast({
          title: '签字成功',
        });

        // setTimeout(() => {
        //   uni.navigateBack();
        // }, 500);

        // 更新签字
        if (!signature.value) {
          uploadSignature({
            id: userInfos.id,
            signature: sign,
          });
        }
        showAction.value = false;
        // 刷新页面
        init(form.id);
      } else {
        uni.showToast({
          mask: true,
          title: `签字失败,原因${res.msg}`,
          icon: 'none',
        });
      }
    })
    .finally(() => {
      uni.hideLoading();
      // uni.$off('pm-requirement-sign');
    });
};

const signThis = () => {
  const sign = signature.value;
  signHanle(sign);
};

const signReset = () => {
  uni.$on('pm-requirement-sign', (e) => {
    console.log('sign', e);
    signHanle(e);
  });
  uni.navigateTo({
    url: '/pages/pm/requirement/autograph',
  });
};

const selectrdDocumentsPostDictList = async () => {
  try {
    const res = await selectrdDocumentsPostUser({
      webSql: `documents_code = '6'`,
      size: 1000,
    });
    if (res.code !== 0) {
      return;
    }
    rdProjectUserList.value = res.data.records;
  } catch (err) {
    console.log('err', err);
  }
};

const selectrdDocumentsPostUserFn = () => {
  const userInfos = userStore.userInfos;
  const cusPerson = userInfos.user.username;

  selectrdDocumentsPostUser({
    webSql: `user_code = ${cusPerson} and documents_code = 6`,
    size: 1000,
  })
    .then((res) => {
      if (res.code == 0) {
        if (res.data.records.length) {
          const lrs = res.data.records.find(
            (item) => item.reviewFlag == 1 && item.signatureFlag == 1,
          );
          const lr = res.data.records.find((item) => item.reviewFlag == 1);
          const l = res.data.records;
          let o: any = {};

          if (lrs.length) {
            o = lrs[0];
          } else if (lr.length) {
            o = lr[0];
          } else {
            o = l[0];
          }
          postUserObj.value = o;
          if (o.reviewFlag == 1 || o.signatureFlag == 1) {
            showSign.value = true;
          } else {
            showSign.value = false;
          }
        } else {
          showSign.value = false;
        }
      } else {
        showSign.value = false;
      }
    })
    .catch(() => {
      showSign.value = false;
    });
};

// type 0 获取姓名 1 获取签名
const getProjectName = (item, type = 0) => {
  console.log(reviewForm.rdProjectUserEntity, item);
  const l = reviewForm.rdProjectUserEntity.filter((f) => f.userType == item.documentsPostCode);
  let s = '';
  if (l.length) {
    console.log('s', s);
    if (type == 0) {
      s = l.map((item) => item.userName).join(',');
      return s;
    } else {
      // s = l.map((item) => item.userUrl).join(',');
      s = l[0]['userUrl'];
      return s;
    }
  } else {
    return s;
  }
};

const getrdDemandDeviceObjHandle = () => {
  console.log('reviewForm', reviewForm.id);
  getrdDemandDeviceObj(reviewForm.id)
    .then((res) => {
      console.log('res', res);
      if (res.code === 0) {
        Object.assign(reviewForm, res.data);
      } else {
        uni.showToast({
          mask: true,
          icon: 'none',
          title: `获取数据失败， 失败原因：${res.msg}`,
        });
      }
    })
    .catch((err) => {
      console.log('err', err);
    });
};
</script>

<style lang="scss" scoped>
@import '../experiment/components/table';

.card-detail {
  padding: 0 !important;
}

.wd-cell {
  padding-left: 0 !important;
}

.wd-card__title {
  border-left: 4px solid #2e5cf6 !important;
}

.pm-table {
  box-sizing: border-box;
  display: flex;
  flex-direction: column;
  padding: 0 30rpx;

  .pm-title {
    box-sizing: border-box;
    padding-left: 20rpx;
    margin: 40rpx 0;
    font-size: 32rpx;
    font-weight: bold;
    color: #333;
    border-left: 8rpx solid #2e5cf6;
    border-radius: 4rpx;
  }

  .pm-row {
    display: flex;
    min-height: 60rpx;
    border-bottom: 1px solid #f6f0f0;

    .pm-label {
      display: flex;
      align-items: center;
      width: 20%;
      font-size: 26rpx;
      color: #979494;
    }

    .pm-value {
      display: flex;
      flex: 1;
      align-items: center;
      font-size: 26rpx;
      color: #333;
    }
  }
}

.sign-main {
  // display: flex;
  // align-items: center;
  // justify-content: center;
  // width: 100%;
  // margin: 20rpx 0;
  position: fixed;
  right: 0rpx;
  bottom: 40rpx;
  width: 160rpx;
  height: 80rpx;
  line-height: 80rpx;
  color: white;
  text-align: center;
  background-color: rgb(77 128 240);

  // border-radius: 50%;
  border-top-left-radius: 40rpx;
  border-bottom-left-radius: 40rpx;
}

:deep(.label) {
  width: 160rpx !important;
}

.result-tag {
  padding: 6rpx 14rpx;
  font-size: 24rpx;
  color: white;
  background-color: #87d068;
  border-radius: 4rpx;
}

.sign-main-show {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;

  .sign-main-show-title {
    display: flex;
    align-items: center;
    justify-content: center;
    width: 100%;
    height: 80rpx;
    margin-bottom: 20rpx;
    font-size: 30rpx;
    font-weight: bold;
    color: #818181;
    border-bottom: 1px solid #e3e3e3;
  }

  .sign-main-show-line {
    box-sizing: border-box;
    display: flex;
    align-items: center;
    justify-content: center;
    width: 90%;
    padding: 20rpx;
    margin: 20rpx 0;
    border: 4rpx solid #d0dbff;
    border-radius: 10rpx;
  }

  .sign-main-show-btn {
    display: flex;
    align-items: center;
    justify-content: center;
    width: 100%;
    height: 80rpx;
    border-top: 1px solid #e3e3e3;
  }
}

.sign-gray {
  background-color: gray;
}

.form-demandDesc {
  align-items: flex-start !important;
}

.form-CheckTarget {
  flex-direction: column !important;
  align-items: start !important;
}
</style>
